package cn.acewill.yxd.yunxundian.ui.schedule;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Point;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import cn.acewill.yxd.yunxundian.BaseActivity;
import cn.acewill.yxd.yunxundian.R;
import cn.acewill.yxd.yunxundian.YXDAPP;
import cn.acewill.yxd.yunxundian.adapter.UserTaskAdapter;
import cn.acewill.yxd.yunxundian.componet.NetWorkStateReceiver;
import cn.acewill.yxd.yunxundian.componet.calendar.CalendarView;
import cn.acewill.yxd.yunxundian.model.Schedule;
import cn.acewill.yxd.yunxundian.pubClass.AsynData;
import cn.acewill.yxd.yunxundian.pubClass.pubClass;
import cn.acewill.yxd.yunxundian.ui.MainActivity;


/**
 * Created by AAA on 2017/4/17.
 */

public class ScheduleMainActivity extends BaseActivity implements View.OnClickListener{

    protected static YXDAPP yxdapp=new YXDAPP();
    protected static DbManager db = x.getDb(yxdapp.getDaoConfig());
    private int year_c = 0;// 今天的年份
    private int month_c = 0;// 今天的月份
    private int day_c = 0;// 今天的日期
    private static UserTaskAdapter adapter;
    public static TextView currentYear,currentWeek,currentMonth;
    private CalendarView myCalender;
    private static ListView myTaskList;
    private static ArrayList<Schedule> taskList;
    private Dialog dialog;
    private AsynData ad=new AsynData(null);
    public static Context mContext;
    NetWorkStateReceiver netWorkStateReceiver;

    @Override
    protected void onResume() {
        if (netWorkStateReceiver==null){
            netWorkStateReceiver=new NetWorkStateReceiver();
        }
        IntentFilter filter=new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(netWorkStateReceiver,filter);
        System.out.print("广播注册");
        super.onResume();
    }

    @Override
    protected void onPause() {
        unregisterReceiver(netWorkStateReceiver);
        System.out.print("广播注销");
        super.onPause();
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.schedule_mian);
        super.onCreate(savedInstanceState);
        initView();

    }
    public void initView() {
        mContext=this;
        Button moreBtn = (Button) findViewById(R.id.MoreBtn);
        ImageView backBtn = (ImageView) findViewById(R.id.backBtn);
        backBtn.setOnClickListener(this);
        moreBtn.setOnClickListener(this);
        currentYear= (TextView) findViewById(R.id.currentYear);
        currentWeek= (TextView) findViewById(R.id.currentWeek);
        currentMonth= (TextView) findViewById(R.id.currentMonth);

        myTaskList= (ListView) findViewById(R.id.myTaskList);
        myCalender = (CalendarView) findViewById(R.id.myCalender);
        setCurrentDay();
        LoadScheduleData();
        myCalender.setClickDataListener(new CalendarView.ClickDataListener() {
            @Override
            public void clickData(String year, String month, String day) {
                year_c=Integer.parseInt(year);
                month_c=Integer.parseInt(month);
                day_c=Integer.parseInt(day);
                myCalender.setDay_j(day_c);
                setTitle();
                LoadScheduleData();
                adapter.notifyDataSetChanged();
            }
        });
    }
    //	获取到当前的时间
    private void  setCurrentDay() {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        String currentDate = sdf.format(date);
        year_c = Integer.parseInt(currentDate.split("-")[0]);
        month_c = Integer.parseInt(currentDate.split("-")[1]);
        day_c = Integer.parseInt(currentDate.split("-")[2]);
        setTitle();
    }
    public void setTitle(){
        currentYear.setText(year_c+"年");
        currentMonth.setText(month_c+"月");
        currentWeek.setText(day_c+"日");
    }

    public static void setTitleForCal(int year,int month,int day)
    {
        currentYear.setText(year+"年");
        currentMonth.setText(month+"月");
        currentWeek.setText(day+"日");
        LoadScheduleData(year,month,day);
    }

    //region 日程信息同步
    public void LoadScheduleData() {
        String mm= String.valueOf(month_c);
        String dd=String.valueOf(day_c);
        if(mm.length()==1)
        {
            mm="0"+mm;
        }
        if(dd.length()==1){
            dd="0"+dd;
        }

        try{
            List<Schedule> tempsch=db.selector(Schedule.class).where("schStartTime","like",year_c+"-"+mm+"-"+dd+"%").and("toUserId", "=", MainActivity.id).orderBy("sTypeID").findAll();
            taskList=new ArrayList<>();
            if(tempsch!=null)
            {
                for(Schedule s:tempsch)
                {
                    taskList.add(s);
                }

                adapter=new UserTaskAdapter(ScheduleMainActivity.this,taskList);
                myTaskList.setAdapter(adapter);
                myTaskList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        Schedule schedule= (Schedule) parent.getItemAtPosition(position);
                        showAnimaDialog(ScheduleMainActivity.this,schedule.getTitle());
                    }
                });
            }
        }
        catch (DbException e){

        }
    }

    public static void LoadScheduleData(int year,int month,int day) {
        String mm= String.valueOf(month);
        String dd=String.valueOf(day);
        if(mm.length()==1)
        {
            mm="0"+mm;
        }
        if(dd.length()==1){
            dd="0"+dd;
        }

        try{
            List<Schedule> tempsch=db.selector(Schedule.class).where("schStartTime","like",year+"-"+mm+"-"+dd+"%").and("toUserId", "=", MainActivity.id).orderBy("sTypeID").findAll();
            taskList=new ArrayList<>();
            if(tempsch!=null)
            {
                taskList.addAll(tempsch);

                adapter=new UserTaskAdapter(mContext,taskList);
                myTaskList.setAdapter(adapter);
                myTaskList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        Schedule schedule= (Schedule) parent.getItemAtPosition(position);
                        showAnimaDialog(mContext,schedule.getTitle());
                    }
                });
            }
        }
        catch (DbException e){

        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.MoreBtn:
                dialog=new Dialog(this);
                View view= LayoutInflater.from(this).inflate(R.layout.schedule_more_dialog,null);
                Button closedialog= (Button) view.findViewById(R.id.closeDialog);
                closedialog.setOnClickListener(this);
                TextView addOther= (TextView) view.findViewById(R.id.addOther);
                addOther.setOnClickListener(this);
                TextView projectTask= (TextView) view.findViewById(R.id.projectTask);
                projectTask.setOnClickListener(this);
                TextView copyTask= (TextView) view.findViewById(R.id.copyTask);
                TextView checkTask = (TextView) view.findViewById(R.id.checkTask);
                checkTask.setOnClickListener(this);
                copyTask.setOnClickListener(this);
               dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                dialog.setContentView(view);
                Window dialogWindow=dialog.getWindow();
                WindowManager m=getWindowManager();
                WindowManager.LayoutParams lp=dialogWindow.getAttributes();
                dialogWindow.setGravity(Gravity.LEFT|Gravity.TOP);
                //获取屏幕宽高
                Display d=m.getDefaultDisplay();
                Point size=new Point();
                d.getSize(size);
                lp.x=0;
                lp.y=0;
//                int width=size.x;
//                int height=size.y;
                lp.height=(int) (d.getHeight()*0.50);
                lp.width=d.getWidth();
                dialogWindow.setAttributes(lp);
                dialog.show();
                break;
            case R.id.closeDialog:
                dialog.dismiss();
                break;
            case R.id.addOther:
                startActivity(new Intent(this,ScheduleAddOtherActivity.class));
                dialog.dismiss();
                break;
            case R.id.addTask:
                if(NetWorkStateReceiver.whetherConnectNetWork==1) {
                    Intent in = new Intent(this, schAdd.class);
                    startActivityForResult(in, 100);
                    dialog.dismiss();
                }
                else if(NetWorkStateReceiver.whetherConnectNetWork==0)
                {
                    showAnimaDialog(ScheduleMainActivity.this,"请检查网络连接");
                }
                break;
            case R.id.projectTask:
                Intent in = new Intent(this, tuisongSchedule.class);
                startActivityForResult(in, 100);
                break;
            case R.id.copyTask:

                break;
            case R.id.backBtn:
                myCalender.resetYearAndMonth();
                setResult(100);
                finish();
                break;
            /*日程检验*/
            case R.id.checkTask:
                startActivity(new Intent(this,ScheduleCheckTaskActivity.class));
                break;
        }
    }

    @Override
    public void onBackPressed() {
        //Log.i(TAG, "onBackPressed");
        setResult(100);
        super.onBackPressed();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (resultCode) { //resultCode为回传的标记，我在B中回传的是RESULT_OK
            case 100:
                ad.asynScheduleDataWithCallBack(MainActivity.id,new pubClass.MyCallBack<String>() {
                    @Override
                    public void onSuccess(String result) {
                        ad.asynScheduleData(result);
                        LoadScheduleData();
                        adapter.notifyDataSetChanged();
                    }
                });
                break;
            default:
                ad.asynScheduleDataWithCallBack(MainActivity.id,new pubClass.MyCallBack<String>() {
                    @Override
                    public void onSuccess(String result) {
                        ad.asynScheduleData(result);
                        LoadScheduleData();
                        adapter.notifyDataSetChanged();
                    }
                });
                break;
        }
    }

}
